package com.totcy.atom.model;

import android.content.Context;

import com.totcy.atom.bean.User;
import com.totcy.atom.net.HttpManager;
import com.totcy.atom.net.subscriber.BaseHttpSubscriber;
import com.totcy.atom.presenter.contract.LoginContract;
import com.totcy.baselibrary.base.mvpbase.BaseModelImpl;

import java.util.TreeMap;

/**
 * description: 登录界面 model层
 * author: Totcy
 * date: 2017/10/30 16:14
 * update: 2017/10/30
 */

public class LoginModel extends BaseModelImpl implements LoginContract.Model {

    private BaseHttpSubscriber<User> subscriber;

    public LoginModel(Context context) {
        super(context);
    }

    @Override
    public void canCelRequest() {
        if (subscriber != null)
            subscriber.unSubscribe();
    }

    @Override
    public void doLogin(String account, String password, final DataCallback callback) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("user_login", account);
        params.put("user_pass", password);
        HttpManager.getApiService(mContext)
                .doLogin(params)
                .compose(HttpManager.<User>applySchedulers())
                .compose(HttpManager.<User>handleResult())
                .subscribe(subscriber = new BaseHttpSubscriber<User>() {
                    @Override
                    public void onSuccess(User user) {
                        callback.onLoginResult(user);
                    }

                    @Override
                    public void onError(int code, String errorMsg) {
                        callback.onLoginFail(errorMsg);
                    }
                });
    }
}
